package com.selfmade.transferutil.excel;

import android.os.Environment;
import android.util.Log;

import com.selfmade.transferutil.model.Book;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

import jxl.Sheet;
import jxl.Workbook;

/**
 * Created by liming on 2016/8/16.
 */
public class SelectExcelFile {

    private String fileDir;                                 //文件路径
    private ArrayList<Book> bookList;

    public SelectExcelFile() {
        bookList = null;
        this.fileDir = getSDPath() + File.separator + "book.xls";
        try{
            Runtime runtime = Runtime.getRuntime();
            runtime.exec("chmod 777 " + fileDir);
        }catch (Exception e){
            e.printStackTrace();
        }
        bookList = new ArrayList<>();
        getAllByExcel();
    }

    public ArrayList<Book> getBookList() {
        return bookList;
    }

    /**
     * 读取xls数据
     */
    private void getAllByExcel(){
        try {
            Workbook rwb = Workbook.getWorkbook(new File(fileDir));
            Sheet rs = rwb.getSheet(0);
            int clos = rs.getColumns();//所有列
            int rows = rs.getRows();//所有行
            Log.d("book", "列：" + Integer.toString(clos));
            Log.d("book", "行：" + Integer.toString(rows));
            for (int i = 0; i < rows; i++) {
                for (int j = 0; j < clos; j++) {//一行行的读出表格中的数据
                    String id = rs.getCell(j++, i).getContents();
                    String name = rs.getCell(j++, i).getContents();
                    String author = rs.getCell(j++, i).getContents();
                    String press = rs.getCell(j++, i).getContents();
                    bookList.add(new Book(id, name, author, press));
                    Log.d("book", "id:" + id + " name:" + name + " author:" + author+ " press:" + press);
                }
            }
            Log.d("book", Integer.toString(clos));
        } catch (Exception e) {
            e.printStackTrace();
            Log.d("book", e.getMessage());
        }
    }

    public String getSDPath() {
        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
        if (sdCardExist) {
            sdDir = Environment.getExternalStorageDirectory();
        }
        String dir = sdDir.toString();
        return dir;
    }
}